package com.byq.mm.smartlib.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.byq.mm.abstractx.cluster.client.DeviceClient;
import com.byq.mm.abstractx.cluster.client.event.ClusterChangeEvent;
import com.byq.mm.abstractx.device.AutomobileType;
import com.byq.mm.abstractx.device.Cluster;
import com.byq.mm.abstractx.device.Device;
import com.byq.mm.application.cluster.client.OnoffClient;
import com.byq.mm.application.cluster.client.SimpleSensorClient;
import com.byq.mm.application.cluster.provider.OnoffProvider;
import com.byq.mm.smartlib.application.MySmartApplication;
import com.byq.mm.smartlib.R;
import com.byq.mm.smartlib.component.SensorView;
import com.byq.mm.smartlib.SmartActionConstants;
import com.byq.mm.smartlib.component.SmartGestureListener;
import com.byq.mm.smartlib.cluster.activity.client.ClientClusterActivityManager;

import com.byq.mm.cluster.provider.SimpleSensorProvider;


import com.byq.mm.smartlib.tools.IconManager;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;
interface Updator{
	void update();
}
public class AutomobileRemoteActivity extends AbstractSmartActivity {

    View sensorContainer;
	View deviceContainer;
	View otherContainer;
    GridView sensorGrid;
	GridView deviceGrid;
	GridView otherGrid;
	
	ViewFlipper flipper;

	private GestureDetector gesture;
	private BroadcastReceiver updateReceiver;
	DeviceClient device;
	Map<String, Updator> updaters = new HashMap<String, Updator>();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.automobile);
        String globalId = this.getIntent().getExtras().getString("globalId");
	    device = application.getAndroidSmartEngine().getCoreEngine().getClientDeviceManager().getDeviceClient(globalId);

        flipper = (ViewFlipper) findViewById(R.id.automobileFlipper);
        sensorContainer = findViewById(R.id.sensorContainer);
        deviceContainer = findViewById(R.id.deviceContainer);
        otherContainer = findViewById(R.id.otherContainer);


        sensorGrid = (GridView) findViewById(R.id.sensorGrid);
        deviceGrid = (GridView) findViewById(R.id.deviceGrid);
        otherGrid = (GridView) findViewById(R.id.otherGrid);

        sensorGrid.setAdapter(new SensorAdapter());
        deviceGrid.setAdapter(new OnoffAdapter());
        otherGrid.setAdapter(new OtherAdapter());
       		gesture = new GestureDetector(new SmartGestureListener(flipper));
       		
       		updateReceiver = new BroadcastReceiver() {
    			@Override
    			public void onReceive(Context context, Intent intent) {
    				String globalId = intent.getExtras().getString("globalId");
    				String clusterId = intent.getExtras().getString("clusterId");
    				ClusterChangeEvent e = (ClusterChangeEvent)intent.getExtras().get("event");
    				Updator up = updaters.get(globalId + clusterId);
    				if(up != null){
    					up.update();
    					MySmartApplication app = (MySmartApplication) application;
    					app.getSound().playSound(0);
    				}
    			}

    		
    		};

    		IntentFilter listFilter =  new IntentFilter();
    		listFilter.addAction(SmartActionConstants.CLUSTER_CLIENT_UPDATED);
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
			registerReceiver(updateReceiver, listFilter, RECEIVER_NOT_EXPORTED);
		}

    }

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		this.unregisterReceiver(updateReceiver);
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		boolean b = super.dispatchTouchEvent(ev);
		//if (!b)
			gesture.onTouchEvent(ev);
		return b;

	}
    void login(){
    	application.getAndroidSmartEngine().getXmppEngine().getConnectionManager().login(false);
    }
    void logout(){
    	application.getAndroidSmartEngine().getXmppEngine().getConnectionManager().logout();
   }
	
	private void updateView() {
		// TODO Auto-generated method stub
		
	}
	class SensorEntity implements Updator{
		SensorView view;
		Device cdevice;
		SimpleSensorClient client;
		public SensorEntity(String type){
			
			
			cdevice = device.getDevice().getSubdeviceByType(type);
			client = (SimpleSensorClient)application.getAndroidSmartEngine().getCoreEngine().getClientDeviceManager().getDeviceClient(cdevice.getGlobalId()).getClusterClient(SimpleSensorProvider.Define.CLUSTER_NAME);
			view = new SensorView(AutomobileRemoteActivity.this,(int)client.getRange().getMax(),(int)client.getValue().getValue(), (short)0, IconManager.getString(AutomobileRemoteActivity.this,type));
			
		}
		public void update(){
			int dd = (int) client.getValue().getValue();
			int max = (int) client.getRange().getMax();
			view.update(dd, max);
			
		}
	}
	class SensorAdapter extends BaseAdapter{
		
		SensorEntity[] views;
		
		public SensorAdapter() {
			super();
			views = new SensorEntity[]{
					new SensorEntity(AutomobileType.Battery),
					new SensorEntity(AutomobileType.Fuel),
					new SensorEntity(AutomobileType.SmoothFuel)
					};
			for(SensorEntity e : views){
				updaters.put(e.client.getDevice().getGlobalId() + e.client.getCluster(), e);
				e.client.readRange();
			}
			
		}

		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return 3;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if(convertView == null)
			{
				convertView = views[position].view;
				AbsListView.LayoutParams lp = new AbsListView.LayoutParams(
						150,200);
				
				convertView.setLayoutParams(lp);
			}
			return convertView;
		}
		
	}
class OnoffEntity implements Updator{
	View view;
	OnoffClient client;
	ImageView i;
	TextView t;
	OnoffEntity(Device device){
		LayoutInflater mInflater = LayoutInflater.from(AutomobileRemoteActivity.this);
		 view = mInflater.inflate(R.layout.grid_item_icon_text, null);

		 i = (ImageView) view.findViewById(R.id.icon);
		 
		 i.setLayoutParams(new LinearLayout.LayoutParams(70, 70));
		 t = (TextView) view.findViewById(R.id.text);
    	i.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				client.toggle();
				
			}
		});
    	
		 
        i.setScaleType(ImageView.ScaleType.FIT_CENTER);
        
        client = (OnoffClient)application.getAndroidSmartEngine().getCoreEngine().getClientDeviceManager().getDeviceClient(device.getGlobalId()).getClusterClient(OnoffProvider.Define.CLUSTER_NAME);
        update();
        client.refresh();
	}
	@Override
	public void update() {
		String dct = client.getDevice().getType();
		String name = IconManager.getString(AutomobileRemoteActivity.this, dct);
        t.setText(name);
        Drawable d;
		if(client.isOn())
	         	d = IconManager.getIconDrawable(AutomobileRemoteActivity.this, dct);
	    else
	        	d = IconManager.getGrayIconDrawable(AutomobileRemoteActivity.this, dct);
	     i.setImageDrawable(d);
	    
		
	}
}
class OnoffAdapter extends BaseAdapter{
		
	OnoffEntity[] views;
		
		public OnoffAdapter() {
			super();
			List<Device> oos = new ArrayList<Device>(device.getDevice().getSubdevicesByCluster(OnoffProvider.Define.CLUSTER_NAME));
			views = new OnoffEntity[oos.size()];
			for(int i = 0; i < oos.size(); i++){
	
				views[i] = new OnoffEntity(oos.get(i));
				updaters.put(views[i].client.getDevice().getGlobalId() + views[i].client.getCluster(), views[i]);
			};
			
			
		}

		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return views.length;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			return views[position].view;
		}
		
	}
class OtherAdapter extends BaseAdapter{
	
		Cluster[] cs;
		
		public OtherAdapter() {
			super();
			
			cs = device.getDevice().getSupportedClusters().toArray(new Cluster[0]);
			
			
		}

		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return cs.length;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View view, ViewGroup parent) {
			final Cluster c = cs[position];
			if(view != null)
				return view;
			LayoutInflater mInflater = LayoutInflater.from(AutomobileRemoteActivity.this);
			 view = mInflater.inflate(R.layout.grid_item_icon_text, null);

			ImageView i = (ImageView) view.findViewById(R.id.icon);
			 
			 i.setLayoutParams(new LinearLayout.LayoutParams(70, 70));
			 TextView t = (TextView) view.findViewById(R.id.text);
			 
			 String title = c.getAlias();
			 if(title == null || title.equals("")){
				 int rid = getResources().getIdentifier(c.getId(),  "string",getPackageName());
				 title = getResources().getString(rid);
			 }
			 
			 
			 int irid = getResources().getIdentifier(c.getId(),  "drawable",getPackageName());
			 t.setText(title);
			 i.setImageResource(irid);
			 
	    	i.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					 Class<? extends Activity> type = ClientClusterActivityManager.getActivity(c.getId());
					 Intent it = new Intent(AutomobileRemoteActivity.this,type);
					 it.setPackage(AutomobileRemoteActivity.this.getPackageName());
					 it.putExtra("globalId",device.getDevice().getGlobalId());
					 it.putExtra("clusterId",c.getId());
					 AutomobileRemoteActivity.this.startActivity(it);
					 
					
				}
			});
	    	
			 
	        i.setScaleType(ImageView.ScaleType.FIT_CENTER);

			
			
			return view;
		}
		
	}
}